#include "window.h"
#include <string.h>
#include <stdlib.h>
#include <xcb/xcb.h>  
#include <xcb/xcb_event.h>
#include <xcb/xcb_icccm.h>

extern xcb_connection_t *dpy;

void get_atom(char *name, xcb_atom_t *atom)    
{
    xcb_intern_atom_reply_t *reply = xcb_intern_atom_reply(
            dpy,
            xcb_intern_atom(dpy, 0, strlen(name), name),
            NULL);

    if (reply != NULL) {
        *atom = reply->atom;
    } else {    
        *atom = XCB_NONE;
    }
    free(reply);
}

void set_atom(xcb_window_t win, xcb_atom_t atom, uint32_t value)    
{    
    xcb_change_property(dpy, XCB_PROP_MODE_REPLACE, win, \
            atom, XCB_ATOM_CARDINAL, 32, 1, &value);
}

void set_window_state(xcb_window_t win, xcb_icccm_wm_state_t state)
{
    uint32_t data[] = {state, XCB_NONE};
    // xcb_change_property(dpy, XCB_PROP_MODE_REPLACE, win, \
    WM_STATE, WM_STATE, 32, 2, data);
}

void setup_ewmh(monitor_t *mon)
{
    xcb_atom_t prop;
    xcb_atom_t data[12] = {0};

    get_atom("_NET_WM_WINDOW_TYPE", &prop);
    get_atom("_NET_WM_WINDOW_TYPE_DOCK", data);
    xcb_change_property(dpy,
            XCB_PROP_MODE_REPLACE, mon->window, prop,
            XCB_ATOM_ATOM, 32, 1, data);

    get_atom("_NET_WM_STATE", &prop);
    get_atom("_NET_WM_STATE_STICKY", data);
    xcb_change_property(dpy,
            XCB_PROP_MODE_APPEND, mon->window, prop,
            XCB_ATOM_ATOM, 32, 1, data);
    get_atom("_NET_WM_STATE_ABOVE", data);
    xcb_change_property(dpy,
            XCB_PROP_MODE_APPEND, mon->window, prop,
            XCB_ATOM_ATOM, 32, 1, data);

    if(1) {
        data[2] = mon->h;
        data[8] = mon->x;
        data[9] = mon->x + mon->w - 1;
    } else {
        data[3]  = mon->h;
        data[10] = mon->x;
        data[11] = mon->x + mon->w - 1;
    }
    get_atom("_NET_WM_STRUT_PARTIAL", &prop);
    xcb_change_property(dpy,
            XCB_PROP_MODE_REPLACE, mon->window, prop,
            XCB_ATOM_CARDINAL, 32, 12, data);
    get_atom("_NET_WM_STRUT", &prop);
    xcb_change_property(dpy,
            XCB_PROP_MODE_REPLACE, mon->window, prop,
            XCB_ATOM_CARDINAL, 32, 4, data);
}

